package com.it.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.it.bean.Message;
import com.mysql.jdbc.Connection;


public class MessageDao {
	private Connection conn = null;

	public List<Message> getAll() {
		conn = Dbutils.getConnection();
		String sql = "select * from t_message";
		ResultSet rst = null;
		PreparedStatement prst = null;
		List<Message> messages = new ArrayList<Message>();
		try {
			prst = conn.prepareStatement(sql);
			rst = prst.executeQuery();
			while (rst.next()) {
				Message msg = new Message();
				msg.setId(rst.getInt("id"));
				msg.setNickname(rst.getString("nickname"));
				msg.setTitle(rst.getString("title"));
				msg.setPhone(rst.getString("phone"));
				msg.setContent(rst.getString("content"));
				msg.setCreateTime(rst.getString("createTime"));
				messages.add(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return messages;
	}

	public int addMessage(Message msg) {
		conn = Dbutils.getConnection();
		String sql = "insert into t_message (nickname,title,phone,content,createTime) values (?,?,?,?,?)";
		PreparedStatement prst = null;
		int row = 0;
		try {
			prst = conn.prepareStatement(sql);
			prst.setString(1, msg.getNickname());
			prst.setString(2, msg.getTitle());
			prst.setString(3, msg.getPhone());
			prst.setString(4, msg.getContent());
			prst.setString(5, msg.getCreateTime());
			row = prst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return row;
	}

	public Message getById(Integer id) {
		conn = Dbutils.getConnection();
		String sql = "select * from t_message where id=?";
		PreparedStatement prst = null;
		ResultSet rst = null;
		Message msg = null;
		try {
			prst = conn.prepareStatement(sql);
			prst.setInt(1, id);
			rst = prst.executeQuery();
			while (rst.next()) {
				msg = new Message();
				msg.setId(rst.getInt("id"));
				msg.setNickname(rst.getString("nickname"));
				msg.setTitle(rst.getString("title"));
				msg.setPhone(rst.getString("phone"));
				msg.setContent(rst.getString("content"));
				msg.setCreateTime(rst.getString("createTime"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return msg;
	}

	public int delete(Integer id) {
		conn = Dbutils.getConnection();
		String sql = "delete from t_message where id=?";
		PreparedStatement prst = null;
		int row = 0;
		try {
			prst = conn.prepareStatement(sql);
			prst.setInt(1, id);
			row = prst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return row;
	}
}
